extends Node2D

@onready var ground: TileMapLayer = $TileMap/Ground
@onready var camera_2d: Camera2D = $Player/Camera2D
@onready var canvas_modulate: CanvasModulate = $CanvasModulate
@onready var player: Player = $Player
@onready var death_timer: Timer = $DeathTimer
@onready var start: Marker2D = $Marks/Start
@onready var safe_areas: Node = $SafeAreas
@onready var marks: Node = $Marks

var enemy_mark: Marker2D = null
var time: float = 0.0
var delta_time: float = 0.0

const SAFE_AREA = preload("res://scenes/game_main/safe_area.tscn")
const DIALOGUE_1 = preload("res://resources/dialogues/dialogue1.tres")

func _ready() -> void:
	canvas_modulate.color = Color("1c1c1c")
	
	var used := ground.get_used_rect()
	var tile_size := ground.tile_set.tile_size
	
	camera_2d.limit_top = used.position.y * tile_size.y
	camera_2d.limit_right = used.end.x * tile_size.x
	camera_2d.limit_bottom = used.end.y * tile_size.y
	camera_2d.limit_left = used.position.x * tile_size.x
	camera_2d.reset_smoothing()
	
	await get_tree().create_timer(1).timeout
	GameManager.instance_node(SAFE_AREA, safe_areas, start.global_position)
	SoundManager.play_sfx("KaiGuan")
	
	await get_tree().create_timer(1).timeout
	GameManager.player_should = true
	GameManager.dialogue_ui.show_dialogue(DIALOGUE_1)
	
	delta_time = randf_range(-1.0, 5.0)
	#create_enemy()

func _physics_process(delta: float) -> void:
	if enemy_mark:
		var vec1 := player.global_position - get_global_mouse_position()
		var vec2 := player.global_position - enemy_mark.global_position
		#print(vec1.angle_to(vec2))
		if absf(vec1.angle_to(vec2)) < deg_to_rad(15) and player.light_state:
			enemy_death()
	elif not player.in_safe and time >= 10 + delta_time:
		create_enemy()
	elif player.in_safe:
		enemy_death()
	
	time += delta

func create_enemy():
	print("创建敌人")
	var vec := (get_global_mouse_position() - player.global_position).normalized()
	var pos: Vector2 = player.global_position - 10 * vec
	var mark := Marker2D.new()
	marks.add_child(mark)
	mark.global_position = pos
	enemy_mark = mark
	#print(get_global_mouse_position(),player.global_position,pos,vec)
	death_timer.start()
	SoundManager.play_sfx("Monster")

func enemy_death():
	print("敌人死亡")
	death_timer.stop()
	if enemy_mark:
		enemy_mark.queue_free()
	time = 0.0
	delta_time = randf_range(-1.0, 5.0)

func _on_death_timer_timeout() -> void:
	if player.in_safe:
		enemy_death()
		return
	if not enemy_mark:
		return
	print("抓到玩家了")
	player.die()
